# Create your views here.
from django.http import HttpResponse
from django.template import RequestContext, loader
from fetchemApp.forms import *
from django.shortcuts import render, redirect
from fetchemApp.models import *
import datetime
from django.utils import timezone
import checkSubIdPass
import ExcelImport
import ExcelExport
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib import auth
import Reg_notification
import os
import shutil
from django.conf import settings

import AssignmentFetch, SendMail

def login(request):
    loggedInUsingUnknownAccount = False
    badEmail = ''
    if request.user.is_authenticated():
        sessionUser = request.session.get('user_id', 'none')
        if(sessionUser!='none'):
            # Means someone is already logged in!
            userObj = Grader.objects.get(pk=sessionUser)
            cCourse = userObj.course_set.all()
            if not cCourse:
                return redirect('/new')
            else:
                courseID = cCourse[0].pk
                return redirect('/course-'+ str(int(courseID)))
        email = request.user.email
        try:
            graderObject = Grader.objects.get(Email=email)
        except Grader.DoesNotExist:
            #Means the person is not registered in our DB.
            loggedInUsingUnknownAccount = True
            badEmail = request.user.email
            return render(request, 'fetchemApp/login.html', {'badLogin':loggedInUsingUnknownAccount, 'badEmail':badEmail})
        request.session['user_id'] = graderObject.id
        return redirect('/')
    #t = loader.get_template('fetchemApp/login.html')
    #c = RequestContext(request, {'hello': 'Hi!'})
    return render(request, 'fetchemApp/login.html', {'badLogin':loggedInUsingUnknownAccount, 'badEmail':badEmail})

def index(request, course=None, assignment=None, submission=None):
    sessionUser = request.session.get('user_id', 'none')
    openCourseModal = False
    openAssignmentModal = False
    afterExcelImportModal = False
    newSubmissionForm = submissionForm()
    if(sessionUser!='none'):
        #### We can use this dictionary to pass any misc args, rather than adding one each time.
        miscArgs ={'passValFail': False, 'courseCreateLoginFailed': False, 'invalidExcelSheet': False}
        #### ^This dictionary.
        if(course==None):
            try:
                userObj = Grader.objects.get(pk=sessionUser)
            except:
                return redirect('/logout')
            return redirect('/course-' + str(userObj.course_set.all()[0].id))
        elif ((course!=None) and (assignment == None)):
            cCourse = Course.objects.get(pk=course)
            if not cCourse.assignment_set.all():
                return redirect('/course-' + str(course) +'/assignment-0')
            else:
                return redirect('/course-' + str(course) + '/assignment-' +str(cCourse.assignment_set.all()[0].id))
        elif ((assignment!=None) and (assignment!='0') and (submission == None)):
            cCourse = Course.objects.get(pk=course)
            cAssignment = Assignment.objects.get(pk=assignment)
            if not cAssignment.submission_set.all():
                return redirect('/course-' + str(course) + '/assignment-' + str(assignment) +'/0')
            else:
                return redirect('/course-' + str(course) + '/assignment-' + str(assignment) +'/'+ str(cAssignment.submission_set.all()[0].id))
        userObj = Grader.objects.get(pk=sessionUser)
        
         
        cCourse = Course.objects.get(pk=course)
        myCourses = Course.objects.filter(Graders=userObj)
        if not (cCourse in myCourses):
            return redirect('/course-' + str(userObj.course_set.all()[0].id))
        if (submission == '0'):
            noSubmission = 'Yes'
            noAssignment = 'No'
            cAssignment = Assignment.objects.get(pk=assignment)
            cAssignments = Assignment.objects.filter(course=cCourse)
            cTAs = cCourse.Graders.all()
            allStudents = cCourse.Students.all()
        
            assnSettingsf = assignmentSettingsForm(assn_object=cAssignment)
            cStudents = []
            for i in cCourse.Students.all():
                if not Submission.objects.filter(assignment=cAssignment,student=i):
                    cStudents+= [i]
        elif (assignment=='0'):
            noAssignment ='Yes'
            cTAs = cCourse.Graders.all()
            allStudents = cCourse.Students.all()
        else:
            noSubmission = 'No'
            noAssignment = 'No'
            cAssignment = Assignment.objects.get(pk=assignment)
            cSubmission = Submission.objects.get(pk=submission)
            assnSettingsf = assignmentSettingsForm(assn_object=cAssignment)
            cAssignments = Assignment.objects.filter(course=cCourse)
            cTAs = cCourse.Graders.all()
            allStudents = cCourse.Students.all()
            
            cStudents = []
            for i in cCourse.Students.all():
                if not Submission.objects.filter(assignment=cAssignment,student=i):
                    cStudents+= [i]
            cSubmissions = Submission.objects.filter(assignment=cAssignment)
            
            if(type(cSubmission) == type(Submission.objects.all()[0]) and len(cSubmission.questiongrade_set.all())!=0):
                Graded=True
            else:
                Graded=False
            newSubmissionForm = submissionForm(subObject=cSubmission, AssnObject=cAssignment, alreadyGraded=Graded)
        
        t = loader.get_template('fetchemApp/index.html')
        
        #Handle if POST or GET
        if request.method == 'POST':
            if 'submissionSave' in request.POST or 'submissionMark' in request.POST or 'submissionSaveSend' in request.POST:
                print 'Submission Save pressed!'
                Send=False
                Review=False
                if 'submissionSaveSend' in request.POST:
                    Send=True
                if 'submissionMark' in request.POST:
                    Review=True
                newSubmissionForm = submissionForm(data=request.POST, subObject=cSubmission, AssnObject=cAssignment)
                newAssignmentf = newAssignmentForm()
                newCoursef = newCourseForm()
                courseSettingsf = courseSettingsForm(course_object=cCourse)
                assnSettingsf = assignmentSettingsForm()

                if(newSubmissionForm.is_valid()):
                    newSubObject = Submission.objects.get(pk=cSubmission.id)
                    if(newSubObject.Status != 'Graded' and newSubObject.Status != 'Sent' and newSubObject.Status !='Marked'):
                        newSubObject.Comment = newSubmissionForm.cleaned_data['Comments']
                        newSubObject.BonusPenaltyType = newSubmissionForm.cleaned_data['BPType']
                        newSubObject.BonusPenaltyValue = newSubmissionForm.cleaned_data['BPValue']
                        
                        listOfMainQuestions = cAssignment.question_set.filter(ParentQuestion=None)
                        print 'Length of listOfMainQuestions: ' + str(len(listOfMainQuestions))
                        for z in listOfMainQuestions:
                            marksForX = newSubmissionForm.cleaned_data['Q' + str(z.QNo)]
                            qGrade = QuestionGrade(submission=cSubmission, question=z,Marks=marksForX)
                            qGrade.save()
                    
                        listOfSubQuestions = cAssignment.question_set.all().exclude(ParentQuestion=None)
                        print 'Length of the Other: ' + str(len(listOfSubQuestions))
                        for z in listOfSubQuestions:
                            marksForX = newSubmissionForm.cleaned_data['Q' + str(z.ParentQuestion.QNo) + '.' + str(z.QNo)]
                            qGrade = QuestionGrade(submission=cSubmission, question=z,Marks=marksForX)
                            qGrade.save()
                        newSubObject.Status = "Graded"
                        if(Review): newSubObject.Status = "Marked"
                        if(Send):
                            newSubObject.Status = "Sent"
                        newSubObject.grader = userObj
                        newSubObject.Grade_Timestamp = datetime.datetime.now()
                        newSubObject.save()
                        if(Send):
                            SendMail.sendMarks(newSubObject)
                        newSubmissionForm = submissionForm(subObject=newSubObject, AssnObject=cAssignment, alreadyGraded=True)
                    else:
                        newSubObject.Comment = newSubmissionForm.cleaned_data['Comments']
                        newSubObject.BonusPenaltyType = newSubmissionForm.cleaned_data['BPType']
                        newSubObject.BonusPenaltyValue = newSubmissionForm.cleaned_data['BPValue']
                        
                        listOfMainQuestions = cAssignment.question_set.filter(ParentQuestion=None)
                        for z in listOfMainQuestions:
                            marksForX = newSubmissionForm.cleaned_data['Q' + str(z.QNo)]
                            qGrade = QuestionGrade.objects.get(submission=cSubmission, question=z)
                            qGrade.Marks = marksForX
                            qGrade.save()
                        listOfSubQuestions = cAssignment.question_set.all().exclude(ParentQuestion=None)
                        print 'Length of the Other: ' + str(len(listOfSubQuestions))
                        for z in listOfSubQuestions:
                            marksForX = newSubmissionForm.cleaned_data['Q' + str(z.ParentQuestion.QNo) + '.' + str(z.QNo)]
                            qGrade = QuestionGrade.objects.get(submission=cSubmission, question=z)
                            qGrade.Marks = marksForX
                            qGrade.save()
                        newSubObject.Status = "Graded"
                        if(Review): newSubObject.Status = "Marked"
                        if(Send):
                            newSubObject.Status = "Sent"
                        newSubObject.grader = userObj
                        newSubObject.Grade_Timestamp = datetime.datetime.now()
                        newSubObject.save()
                        if(Send):
                            SendMail.sendMarks(newSubObject)
                        newSubmissionForm = submissionForm(subObject=newSubObject, AssnObject=cAssignment, alreadyGraded=True)
                    
            if 'courseCreate' in request.POST:
                #Initialize the other forms
                newAssignmentf = newAssignmentForm()
                courseSettingsf = courseSettingsForm(course_object=cCourse)
                assnSettingsf = assignmentSettingsForm()
                newCoursef = newCourseForm(request.POST, request.FILES)
                if(newCoursef.is_valid()):
                    #Form data is valid; We can create a course from this.
                    #First check if the two passwords were the same.
                    ExcelResult = ExcelImport.checkExcelSheet(request.FILES['ExcelSheet'])
                    if(newCoursef.cleaned_data['SubPassword']!=newCoursef.cleaned_data['SubPasswordConfirm']):
                        miscArgs['passValFail'] = True
                    #Password confirmation check complete.
                    
                    elif (Course.objects.filter(CourseNo=newCoursef.cleaned_data['CourseNo'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester']).count()>0):
                        miscArgs['DuplicateCourse'] = True
                        dCourseI = Course.objects.get(CourseNo=newCoursef.cleaned_data['CourseNo'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester']).Graders.filter(Type='I')
                        miscArgs['DuplicateCourseError'] = 'The course ' + newCoursef.cleaned_data['CourseNo'] + '-' + str(newCoursef.cleaned_data['Year']) + '-' + newCoursef.cleaned_data['Semester'] + " is already registered in Fetch'em! If this is a mistake, please contact the course instructor " + dCourseI.Name + ' ('+ dCourseI.Email + ')'
                    
                    elif(miscArgs['passValFail']==False and checkSubIdPass.isLoginValid(newCoursef.cleaned_data['SubEmail'], newCoursef.cleaned_data['SubPassword'])==False):
                        miscArgs['courseCreateLoginFailed'] = True
                    elif(ExcelResult!='VALID'):
                        miscArgs['ExcelIssue'] = True
                        if(ExcelResult=='INVALID'):
                            miscArgs['ExcelError'] = 'The file you uploaded is not a valid .xls file! Please select a valid .xls file.'
                            pass
                        elif(ExcelResult=='WRONGFORMAT'):
                            miscArgs['ExcelError'] = 'The file you uploaded is in the wrong format. Please refer to the template provided to make a right format file.'
                            pass
                        elif(ExcelResult=='WRONGRECORD'):
                            miscArgs['ExcelError'] = 'The file you uploaded has wrong data somewhere; Perhaps an invalid email address or an empty cell? Please check and re-upload a valid file.'
                            pass
                        elif(ExcelResult=='EMPTY'):
                            miscArgs['ExcelError'] = 'The file you uploaded is empty! Please select a valid .xls file!'
                            pass
                    else:
                        theNewCourseObject = Course(CourseNo=newCoursef.cleaned_data['CourseNo'], Name=newCoursef.cleaned_data['Name'], SubEmail=newCoursef.cleaned_data['SubEmail'], SubPassword=newCoursef.cleaned_data['SubPassword'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester'])
                        theNewCourseObject.save()
                        
                        #Adding the student list.
                        studentListFile = request.FILES['ExcelSheet']
                        print str(ExcelImport.useStudentList(studentListFile, theNewCourseObject)) + ' was the result of the import!'
                        afterExcelImportModal = True
                        
                        
                        theNewCourseObject.Graders.add(userObj)
                        
                        #Send Notifications to Students
                        Reg_notification.SendRegistrationNotice(theNewCourseObject.Students.all(), theNewCourseObject)
                        
                        if(newCoursef.cleaned_data['TAEmail']!='' and newCoursef.cleaned_data['TAName']!=''):
                            if(Grader.objects.filter(Email=newCoursef.cleaned_data['TAEmail']).count()!=0):
                                PrimaryTA = Grader.objects.get(Email=newCoursef.cleaned_data['TAEmail'])
                            else:
                                PrimaryTA = Grader.objects.create(Name=newCoursef.cleaned_data['TAName'], Email=newCoursef.cleaned_data['TAEmail'], Type='T')
                            theNewCourseObject.Graders.add(PrimaryTA)
                        if(newCoursef.cleaned_data['ExtraEmailCounter']>0):
                            #TODO - Validate these extra emails
                            for i in range(newCoursef.cleaned_data['ExtraEmailCounter']):
                                if(Grader.objects.filter(Email=request.POST['ExtraTAEmail' + str(i)]).count()!=0):
                                    TAToAdd= Grader.objects.get(Email=request.POST['ExtraTAEmail' + str(i)])
                                else:
                                    TAToAdd = Grader.objects.create(Name=request.POST['ExtraTAName' + str(i)], Email=request.POST['ExtraTAEmail' + str(i)], Type='T')
                                theNewCourseObject.Graders.add(TAToAdd)
                       
                        #Send Notifications to TA's
                        Reg_notification.SendRegistrationNotice(theNewCourseObject.Graders.filter(Type='T'), theNewCourseObject)
                        
                        newCoursef = newCourseForm()
                        myCourses = Course.objects.filter(Graders=userObj)
                        nCourse = myCourses[len(myCourses)-1]
                        return redirect('/course-'+ str(int(nCourse.id)))
                        

                else:
                    openCourseModal = True
                    print 'Not validated!'
            elif 'assignmentCreate' in request.POST:
                #Initialize the other forms
                newCoursef = newCourseForm()
                assnSettingsf = assignmentSettingsForm()
                newAssignmentf = newAssignmentForm(request.POST)
                courseSettingsf = courseSettingsForm(course_object=cCourse)
                if(newAssignmentf.is_valid()):
                    sDT = datetime.datetime.combine(newAssignmentf.cleaned_data['StartDate'], newAssignmentf.cleaned_data['StartTime'])
                    eDT = datetime.datetime.combine(newAssignmentf.cleaned_data['EndDate'], newAssignmentf.cleaned_data['EndTime'])
                    if(eDT < sDT):
                        miscArgs['newAssnFormIssue'] = True
                        miscArgs['newAssnFormIssueError'] = 'End date cannot be before start date! Please choose a valid Start Date and End Date.'
                        openAssignmentModal = True
                    else:
                        newAssignment = Assignment(SubjectLine=newAssignmentf.cleaned_data['SubjectLine'], StartDateTime=datetime.datetime.combine(newAssignmentf.cleaned_data['StartDate'], newAssignmentf.cleaned_data['StartTime']), EndDateTime= datetime.datetime.combine(newAssignmentf.cleaned_data['EndDate'], newAssignmentf.cleaned_data['EndTime']), course=cCourse, MaxMarks=newAssignmentf.cleaned_data['MaxMarksNew'])
                        newAssignment.save()
                        for i in range(newAssignmentf.cleaned_data['noQuestions']):
                            question_object = Question(QNo=(i+1), assignment=newAssignment)
                            question_object.save()
                            for j in range(eval(request.POST['s_Q' + str(i+1)])):
                                sub_ques_object = Question(QNo=(j+1), assignment=newAssignment, ParentQuestion=question_object)
                                sub_ques_object.save()
                        newAssignmentf = newAssignmentForm()
                        cAssignments = Assignment.objects.filter(course=cCourse)
                        if cAssignments:
                            AssignmentID = cAssignments[0].pk
                            return redirect('/course-'+ str(int(course))+'/assignment-'+ str(int(AssignmentID))) 
                else:
                    openAssignmentModal = True
                    print 'Assignment Form not Validated!'                    
            elif 'courseSettings' in request.POST:
                newAssignmentf = newAssignmentForm()
                newCoursef = newCourseForm()
                assnSettingsf = assignmentSettingsForm()
                courseSettingsf = courseSettingsForm(request.POST, request.FILES)
                if(courseSettingsf.is_valid()):
                    #Form data is valid; We can create a course from this.
                    cCourse.CourseNo = courseSettingsf.cleaned_data['CourseNo']
                    cCourse.Name = courseSettingsf.cleaned_data['Name']
                    cCourse.SubEmail = courseSettingsf.cleaned_data['SubEmail']
                    cCourse.SubPassword = courseSettingsf.cleaned_data['SubPassword']
                    cCourse.Year = courseSettingsf.cleaned_data['Year']
                    cCourse.Semester = courseSettingsf.cleaned_data['Semester']
                    cCourse.save()
                    
                    #Adding the student list.
                    if 'ExcelSheet' in request.FILES:
                        studentListFile = request.FILES['ExcelSheet']
                        print str(ExcelImport.useStudentList(studentListFile, cCourse)) + ' was the result of the import!'
                        afterExcelImportModal = True
                    
                    if(courseSettingsf.cleaned_data['ExtraEmailCounter2']>0):
                        #TODO - Validate these extra emails
                        for i in range(courseSettingsf.cleaned_data['ExtraEmailCounter2']):
                            if(Grader.objects.filter(Email=request.POST['ExtraTAEmail2' + str(i)]).count()!=0):
                                TAToAdd= Grader.objects.get(Email=request.POST['ExtraTAEmail2' + str(i)])
                            else:
                                TAToAdd = Grader.objects.create(Name=request.POST['ExtraTAName2' + str(i)], Email=request.POST['ExtraTAEmail2' + str(i)], Type='T')
                            cCourse.Graders.add(TAToAdd)
                            Reg_notification.SendRegistrationNotice(cCourse.Graders.filter(Name=request.POST['ExtraTAName2' + str(i)]), cCourse)
                    if(courseSettingsf.cleaned_data['ExtraStudentEmailCounter']>0):
                        #TODO - Validate these extra emails
                        for i in range(courseSettingsf.cleaned_data['ExtraStudentEmailCounter']):
                            if(Student.objects.filter(Email=request.POST['ExtraStudentEmail' + str(i)]).count()!=0):
                                StudentToAdd= Student.objects.get(Email=request.POST['ExtraStudentEmail' + str(i)])
                            else:
                                StudentToAdd = Student.objects.create(Name=request.POST['ExtraStudentName' + str(i)], Email=request.POST['ExtraStudentEmail' + str(i)], RollNo=request.POST['ExtraStudentRoll' + str(i)])
                            cCourse.Students.add(StudentToAdd)
                            Reg_notification.SendRegistrationNotice(cCourse.Students.filter(Name=request.POST['ExtraStudentName' + str(i)]), cCourse)
                            
                        
                    courseSettingsf = courseSettingsForm(course_object=cCourse)
                    return redirect('/course-'+ str(int(cCourse.id)))
                    

                else:
                    print 'Not validated!'
            elif 'assignmentSave' in request.POST:
                #initialize other forms
                newCoursef = newCourseForm()
                newAssignmentf = newAssignmentForm()
                assignObject = Assignment.objects.get(pk=assignment)
                courseSettingsf = courseSettingsForm(course_object=cCourse)
                assnSettingsf = assignmentSettingsForm(request.POST)
                if(assnSettingsf.is_valid()):
                    sDT = datetime.datetime.combine(assnSettingsf.cleaned_data['StartDateSettings'], assnSettingsf.cleaned_data['StartTimeSettings'])
                    eDT = datetime.datetime.combine(assnSettingsf.cleaned_data['EndDateSettings'], assnSettingsf.cleaned_data['EndTimeSettings'])
                    if(eDT < sDT):
                        miscArgs['openAssnSettingsModal'] = True
                        miscArgs['AssnSettingsIssue'] = True
                        miscArgs['AssnSettingsIssueMessage'] = 'End Date cannot be before the start date!'
                    else:
                        assignObject.MaxMarks = assnSettingsf.cleaned_data['MaxMarks']
                        assignObject.StartDateTime = datetime.datetime.combine(assnSettingsf.cleaned_data['StartDateSettings'], assnSettingsf.cleaned_data['StartTimeSettings'])
                        assignObject.EndDateTime = datetime.datetime.combine(assnSettingsf.cleaned_data['EndDateSettings'], assnSettingsf.cleaned_data['EndTimeSettings'])
                        assignObject.save()
                        #print 'date: ' + assignObject.StartDateTime
                        assnSettingsf = assignmentSettingsForm(assn_object= assignObject)
                else:
                    miscArgs['openAssnSettingsModal'] = True
                    print 'Not validated!'
        else: #GET
            newCoursef = newCourseForm()
            newAssignmentf = newAssignmentForm()
            courseSettingsf = courseSettingsForm(course_object=cCourse)
            #assnSettingsf = assignmentSettingsForm(assn_object=cAssignment)
        
        if (submission == '0'):
            c = RequestContext(request, {'userObj': userObj, 'Courses': userObj.course_set.all(), 'cCourse':cCourse, 'newCourseForm':newCoursef, 'courseSettingsForm':courseSettingsf, 'AssignmentForm': newAssignmentf, 'openCourseModal':openCourseModal, 'openAssignmentModal':openAssignmentModal, 'afterExcelImportModal':afterExcelImportModal, 'cStudents':cStudents , 'assnSettings': assnSettingsf, 'cAssignment':cAssignment, 'cAssignments':cAssignments, 'noSubmission':noSubmission, 'noAssignment':noAssignment,'cTAs':cTAs,'allStudents':allStudents, 'miscArgs':miscArgs})    
        elif (assignment == '0'):
            c = RequestContext(request, {'userObj': userObj, 'Courses': userObj.course_set.all(), 'cCourse':cCourse, 'newCourseForm':newCoursef, 'courseSettingsForm':courseSettingsf, 'AssignmentForm': newAssignmentf, 'openCourseModal':openCourseModal, 'openAssignmentModal':openAssignmentModal, 'afterExcelImportModal':afterExcelImportModal, 'noAssignment':noAssignment,'cTAs':cTAs,'allStudents':allStudents, 'miscArgs': miscArgs})    
        else:    
            c = RequestContext(request, {'userObj': userObj, 'Courses': userObj.course_set.all(), 'cCourse':cCourse, 'newCourseForm':newCoursef, 'courseSettingsForm':courseSettingsf, 'AssignmentForm': newAssignmentf, 'openCourseModal':openCourseModal, 'openAssignmentModal':openAssignmentModal,'afterExcelImportModal':afterExcelImportModal, 'cStudents':cStudents, 'cSubmission':cSubmission, 'cSubmissions':cSubmissions,  'cAssignment':cAssignment, 'assnSettings': assnSettingsf, 'cAssignments':cAssignments, 'noSubmission':noSubmission,'noAssignment':noAssignment, 'subForm': newSubmissionForm,'cTAs':cTAs,'allStudents':allStudents, 'miscArgs': miscArgs})    
        return HttpResponse(t.render(c))
    else:
        return redirect('/')
    
def newcourse(request):
    sessionUser = request.session.get('user_id', 'none')
    openCourseModal = False
    openAssignmentModal = False
    if(sessionUser!='none'):
        try:
                userObj = Grader.objects.get(pk=sessionUser)
        except:
                return redirect('/logout')
        t = loader.get_template('fetchemApp/newcourse.html')
        miscArgs ={'passValFail': False, 'courseCreateLoginFailed': False, 'invalidExcelSheet': False}
        #Handle if POST or GET
        if request.method == 'POST':
        #Initialize the other forms
                newCoursef = newCourseForm(request.POST, request.FILES)
                if(newCoursef.is_valid()):
                    ExcelResult = ExcelImport.checkExcelSheet(request.FILES['ExcelSheet'])
                    #Form data is valid; We can create a course from this.
                    #First check if the two passwords were the same.
                    if(newCoursef.cleaned_data['SubPassword']!=newCoursef.cleaned_data['SubPasswordConfirm']):
                        miscArgs['passValFail'] = True
                    #Password check complete.
                    
                    elif (Course.objects.filter(CourseNo=newCoursef.cleaned_data['CourseNo'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester']).count()>0):
                        miscArgs['DuplicateCourse'] = True
                        dCourseI = Course.objects.get(CourseNo=newCoursef.cleaned_data['CourseNo'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester']).Graders.filter(Type='I')
                        miscArgs['DuplicateCourseError'] = 'The course ' + newCoursef.cleaned_data['CourseNo'] + '-' + str(newCoursef.cleaned_data['Year']) + '-' + newCoursef.cleaned_data['Semester'] + " is already registered in Fetch'em! If this is a mistake, please contact the course instructor " + dCourseI.Name + ' ('+ dCourseI.Email + ')'
                    
                    
                    elif(miscArgs['passValFail']==False and checkSubIdPass.isLoginValid(newCoursef.cleaned_data['SubEmail'], newCoursef.cleaned_data['SubPassword'])==False):
                        miscArgs['courseCreateLoginFailed'] = True
                    elif(ExcelResult!='VALID'):
                        miscArgs['ExcelIssue'] = True
                        if(ExcelResult=='INVALID'):
                            miscArgs['ExcelError'] = 'The file you uploaded is not a valid .xls file! Please select a valid .xls file.'
                            pass
                        elif(ExcelResult=='WRONGFORMAT'):
                            miscArgs['ExcelError'] = 'The file you uploaded is in the wrong format. Please refer to the template provided to make a right format file.'
                            pass
                        elif(ExcelResult=='WRONGRECORD'):
                            miscArgs['ExcelError'] = 'The file you uploaded has wrong data somewhere; Perhaps an invalid email address or an empty cell? Please check and re-upload a valid file.'
                            pass
                        elif(ExcelResult=='EMPTY'):
                            miscArgs['ExcelError'] = 'The file you uploaded is empty! Please select a valid .xls file!'
                            pass
                    else:
                        theNewCourseObject = Course(CourseNo=newCoursef.cleaned_data['CourseNo'], Name=newCoursef.cleaned_data['Name'], SubEmail=newCoursef.cleaned_data['SubEmail'], SubPassword=newCoursef.cleaned_data['SubPassword'], Year=newCoursef.cleaned_data['Year'], Semester=newCoursef.cleaned_data['Semester'])
                        theNewCourseObject.save()
                        
                        #Adding the student list.
                        studentListFile = request.FILES['ExcelSheet']
                        print str(ExcelImport.useStudentList(studentListFile, theNewCourseObject)) + ' was the result of the import!'
                        theNewCourseObject.Graders.add(userObj)
                        
                        #Send Notifications to Students
                        Reg_notification.SendRegistrationNotice(theNewCourseObject.Students.all(), theNewCourseObject)
                        
                        if(newCoursef.cleaned_data['TAEmail']!='' and newCoursef.cleaned_data['TAName']!=''):
                            if(Grader.objects.filter(Email=newCoursef.cleaned_data['TAEmail']).count()!=0):
                                PrimaryTA = Grader.objects.get(Email=newCoursef.cleaned_data['TAEmail'])
                            else:
                                PrimaryTA = Grader.objects.create(Name=newCoursef.cleaned_data['TAName'], Email=newCoursef.cleaned_data['TAEmail'], Type='T')
                            theNewCourseObject.Graders.add(PrimaryTA)
                        if(newCoursef.cleaned_data['ExtraEmailCounter']>0):
                            #TODO - Validate these extra emails
                            for i in range(newCoursef.cleaned_data['ExtraEmailCounter']):
                                if(Grader.objects.filter(Email=request.POST['ExtraTAEmail' + str(i)]).count()!=0):
                                    TAToAdd= Grader.objects.get(Email=request.POST['ExtraTAEmail' + str(i)])
                                else:
                                    TAToAdd = Grader.objects.create(Name=request.POST['ExtraTAName' + str(i)], Email=request.POST['ExtraTAEmail' + str(i)], Type='T')
                                theNewCourseObject.Graders.add(TAToAdd)
                        
                        #Send Notifications to TA's
                        Reg_notification.SendRegistrationNotice(theNewCourseObject.Graders.filter(Type='T'), theNewCourseObject)
                        
                        newCoursef = newCourseForm()
                        return redirect('/course-'+str(theNewCourseObject.id))
                else:
                    openCourseModal = True
                    print 'Not validated!'
        else: #GET
            newCoursef = newCourseForm()
        c = RequestContext(request, {'Name': userObj.Name, 'Courses': userObj.course_set.all(), 'newCourseForm':newCoursef, 'openCourseModal':openCourseModal, 'openAssignmentModal':openAssignmentModal, 'miscArgs': miscArgs})    
        return HttpResponse(t.render(c))
    else:
        return redirect('/')

def fetcher(request, course, assignment, submission=None):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        cAssignment = Assignment.objects.get(id=assignment)
        AssignmentFetch.fetchMain(cAssignment)
        return redirect('/course-' + str(course) + '/assignment-' + str(assignment))
    else:
        return redirect('/')

def deleteAssignment(request, course, assignment, submission=None):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        if (len(Assignment.objects.filter(pk=assignment, course=course))>0 and len(Course.objects.get(pk=course).Graders.filter(pk=sessionUser)))>0:
            assnObject = Assignment.objects.get(pk=assignment)
            for i in Submission.objects.filter(assignment=assnObject):
                try:
                    os.remove(i.Filename)
                except:
                    pass
            folderPath = os.path.join(settings.MEDIA_ROOT, 'Attachments/'+str(assnObject.course.id)+'_'+str(assnObject.course.CourseNo)+'/'+str(assnObject.SubjectLine))
            try:
                shutil.rmtree(folderPath)
            except:
                pass
            assnObject.delete()
            return redirect('/course-' + str(course))
    return HttpResponse("You're not authorized for this action!")

def deleteCourse(request, course):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        if(len(Course.objects.filter(pk=course))>0):
            g = Grader.objects.get(pk=sessionUser)
            courseObj = Course.objects.get(pk=course)
            if(g.Type=='I' and len(courseObj.Graders.filter(pk=sessionUser))>0):
                #delete course
                folderPath = os.path.join(settings.MEDIA_ROOT, 'Attachments/'+str(courseObj.id)+'_'+str(courseObj.CourseNo))
                try:
                    shutil.rmtree(folderPath)
                except:
                    pass
                courseObj.delete()
                return redirect('/')
    return HttpResponse("Invalid/Unauthorized action!")

def removeTA(request, course,TA):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        cTA = Grader.objects.get(id=TA)
        print cTA
        cTA.delete()
        return redirect('/course-' + str(course))
    return HttpResponse("Invalid/Unauthorized action!")

def removeStudent(request, course, student):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        cCourse = Course.objects.get(pk=course)
        cAssignments = Assignment.objects.filter(course=cCourse)
        studentToRemove = Student.objects.get(id=student)
        submissionsToRemove =[]
        for iAssignment in cAssignments:
            submissionsToRemove.append(Submission.objects.filter(student=studentToRemove).filter(assignment=iAssignment))
            print submissionsToRemove
            for i in submissionsToRemove:
                i.delete()
        cCourse.Students.remove(studentToRemove)
        return redirect('/course-' + str(course))
    return HttpResponse("Invalid/Unauthorized action!")

def excelExport(request, course):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        cCourse = Course.objects.get(pk=course)
        ExcelExport.createSheet(cCourse)
        return redirect('/course-' + str(course))
    return HttpResponse("Invalid/Unauthorized action!")

def notifyAll(request, course, assignment, submission=None):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        cAssignment = Assignment.objects.get(id=assignment)
        SendMail.sendMarks(cAssignment)
        return redirect('/course-' + str(course) + '/assignment-' + str(assignment))
    else:
        return redirect('/')

def serveFile(request, course, assignment, submission):
    sessionUser = request.session.get('user_id', None)
    if(sessionUser!=None):
        aObject = Assignment.objects.get(pk=assignment)
        cObject = Course.objects.get(pk=course)        
        if((cObject.Graders.filter(pk=sessionUser)).exists()):
            if((cObject.assignment_set.filter(pk=assignment)).exists()):
                if((aObject.submission_set.filter(pk=submission)).exists()):
                    filename = Submission.objects.get(pk=submission).Filename
                    response = HttpResponse('This should be changed!') # 200 OK
                    response['content-type'] = 'application/pdf' #It wasn't working without this too.
                    response['X-SendFile'] = filename
                    return response
                else:
                    return HttpResponse('Invalid action; Submission does not belong to this assignment')
            else:
                return HttpResponse('Invalid action; Assignment does not belong to course')
        else:
            return HttpResponse('Invalid action; You are not authorized for this course')
    else:
        return redirect('/')

def logout(request):
    try:
        del request.session['user_id']
    except KeyError:
        pass
    if request.user.is_authenticated():
            auth.logout(request)
    return redirect('/')
